var Editor = {
    //Editor构造方法
    createNew: function (canvas_id) {
        var editor = {};
		
		
		editor.FPS=0;
		editor._FPS=0;
		
		editor.height=600;
		editor.width=900;
		
		
		//file provider
		editor.fileprovider="/file.php";
		
		//debug
		editor.isdebug=false;
        //行高
        editor.row_height = 15;
		
		//是否显示行号
		editor.is_rownumber=true;

		//x 偏移量
		editor.offset_fliechar_x=30;
		
		//y 偏移量
		editor.offset_fliechar_y=50;
		
		//rowNumberRect 行号块
		editor.rowNumberRect={"x":0,"y":editor.offset_fliechar_y,"height":editor.height-editor.offset_fliechar_y+editor.row_height,"width":editor.offset_fliechar_x}
	    
		// 右侧滑块
		editor.rightScrollRect_bg={"x":editor.width-20,"y":editor.offset_fliechar_y,"height":editor.height-editor.offset_fliechar_y+editor.row_height,"width":20}
		editor.rightScrollRect={"x":editor.width-editor.rightScrollRect_bg["width"]+2,"y":editor.offset_fliechar_y,"height":100,"width":editor.rightScrollRect_bg["width"]-4}
		
        //当前打开的对象下标
        editor.open_index = 0;
        //画布ID
        editor.canvas_id = canvas_id;
        //画布对象
        editor.canvas = document.getElementById(editor.canvas_id);
		//console.log(editor.canvas);
		editor.context2D= editor.canvas.getContext("2d");
        editor.mousedown_position;
        editor.mouseup_position;

        //所打开的文件对象列表
        editor.fileList = new Array();

        //打开一个文件
        editor.openfile = function (flieUrl) {
            var efile = EFile.createNew(flieUrl,editor.fileprovider);
            if (checkFile(efile) == false) {
                editor.fileList.push(efile);
				editor.open_index=editor.fileList.length-1;
            }
        };
        //保存一个文件
        editor.save = function (index) {

        };
        //保存所以文件
        editor.saveall = function () {

        };

        //清空一个文件
        editor.clear = function (index) {

        };

        //根据文档设置Canvas
        editor.setPageSize = function (_index) {
			
            var height = editor.row_height*editor.fileList[_index].content.length;
			var width=1000;
			$(editor.canvas).attr("height", editor.height + 10);
			$(editor.canvas).attr("width", editor.width);
			return {"height":height,"width":width};
        };

        //开始
        editor.run = function () {
            setTimeout(editor.show, 16);
			setTimeout(editor.showFps, 1000);
        };
		editor.showFps=function(){
			editor._FPS=editor.FPS;
			editor.FPS=0;
			setTimeout(editor.showFps, 1000);
		}
		
        //show 显示某个文档
        editor.show = function () {
			
			var pageSize=editor.setPageSize(editor.open_index);
			editor.context2D.clearRect(0,0,editor.width,editor.height);
			var maxL=editor.getMaxRows();
			editor.context2D.font = editor.row_height+"px Courier New";
			editor.context2D.textAlign = "left";
			editor.textBaseline="alphabetic";
			
			
	
			//渲染头部文件列表
		    editor.renderHeadFiles();
			
			//渲染行号
			editor.renderNumber();
			
			//渲染文本
			editor.render();

			//渲染右侧滑块
			editor.renderRightScrollRect();
			
			//渲染底部滑块
			
			editor.FPS+=1;
            setTimeout(editor.show, 16);

        };
		
		//获取当前canvas能显示的最大行数
		editor.getMaxRows=function(){
				var height=editor.height-editor.offset_fliechar_y;
				return  Math.round(height/editor.row_height);
		};
		
		//渲染头部文件列表
		editor.renderHeadFiles=function(){
			for(var file_index in editor.fileList){
				console.log(editor.fileList[file_index].name);
			}
		};
		//渲染右侧滑块
		editor.renderRightScrollRect=function(){
			
			var maxL=editor.getMaxRows();
			editor.context2D.fillStyle = "#e1e1e1";
			editor.context2D.fillRect(editor.rightScrollRect_bg["x"],editor.rightScrollRect_bg["y"],editor.rightScrollRect_bg["width"],editor.rightScrollRect_bg["height"]);
			
			editor.context2D.fillStyle = "#000000";
			
			var yhidden_row=editor.fileList[editor.open_index].start_row;
			editor.rightScrollRect["height"]=Math.round((maxL/editor.fileList[editor.open_index].content.length)*editor.rightScrollRect_bg["height"]);
			var y= (editor.rightScrollRect_bg["height"]-editor.rightScrollRect["height"])/(editor.fileList[editor.open_index].content.length-maxL)*(yhidden_row+maxL)-editor.rightScrollRect["height"]
			editor.rightScrollRect["y"]=editor.offset_fliechar_y+y;
			
			editor.context2D.fillRect(editor.rightScrollRect["x"],editor.rightScrollRect["y"],editor.rightScrollRect["width"],editor.rightScrollRect["height"]);
			
		}
		editor.renderNumber=function(){
			//渲染行号背景
			var maxL=editor.getMaxRows();
			var fliechar_y=editor.offset_fliechar_y;
			var fliechar_x=editor.offset_fliechar_x;
			
			editor.context2D.fillStyle = "#e1e1e1";
			
			editor.context2D.fillRect(editor.rowNumberRect["x"],editor.rowNumberRect["y"],editor.rowNumberRect["width"],editor.rowNumberRect["height"]);
			
			
			for (var index=editor.fileList[editor.open_index].start_row;index<editor.fileList[editor.open_index].start_row+maxL;index++) {
				if(index<editor.fileList[editor.open_index].content.length){
					//渲染行号
					editor.context2D.fillStyle = "red";
					fliechar_y=fliechar_y+editor.row_height;
					if(editor.is_rownumber){
						editor.context2D.fillText(parseInt(index)+1, 1, fliechar_y);
					}
				}
			}
			
		};
		
		// 渲染page
		editor.render=function(){
			var fliechar_y=editor.offset_fliechar_y;
			var fliechar_x=editor.offset_fliechar_x;

			//渲染选中文字
			if(editor.fileList[editor.open_index].select_start && editor.fileList[editor.open_index].select_end){

				editor.context2D.fillStyle = "#e1e1e1";

				for(var row=editor.fileList[editor.open_index].select_start["row"];row<=editor.fileList[editor.open_index].select_end["row"];row++){
					
					var start_point;
					var end_point;
					if(row==editor.fileList[editor.open_index].select_start["row"]){
						start_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].select_start["column"]);
						if(row==editor.fileList[editor.open_index].select_end["row"]){
							end_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].select_end["column"]);
						}else{
							end_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].content[row-1].length);
						}
						
						editor.context2D.fillRect(parseInt(start_point["cursor_x"])
						,parseInt(start_point["cursor_y"])-parseInt(end_point["height"])+5
						,parseInt(end_point["cursor_x"])-parseInt(start_point["cursor_x"])
						,parseInt(end_point["height"]));

					}
					else if(row==editor.fileList[editor.open_index].select_end["row"]){

						start_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,0);
						end_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].select_end["column"]);
						editor.context2D.fillRect(parseInt(start_point["cursor_x"]),parseInt(start_point["cursor_y"])-parseInt(end_point["height"])+5,parseInt(end_point["cursor_x"])-parseInt(start_point["cursor_x"]),parseInt(end_point["height"]));
					}
					
					else{
						start_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,0);
						end_point=editor.getPosition(row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].content[row-1].length);
						editor.context2D.fillRect(parseInt(start_point["cursor_x"]),parseInt(start_point["cursor_y"])-parseInt(end_point["height"])+5,parseInt(end_point["cursor_x"])-parseInt(start_point["cursor_x"]),parseInt(end_point["height"]));
					}

				}
				
			}
				
			//渲染文字
			var maxL=editor.getMaxRows();
			
			for (var index=editor.fileList[editor.open_index].start_row;index<editor.fileList[editor.open_index].start_row+maxL;index++) {
				if(index<editor.fileList[editor.open_index].content.length){
					
					editor.context2D.fillStyle = "blue";
					//渲染正文文本
					fliechar_y=fliechar_y+editor.row_height;
					var rowString=editor.fileList[editor.open_index].content[index];
					//var ss=editor.context2D.measureText("x");

					editor.context2D.fillText(rowString, fliechar_x, fliechar_y);
					
				}
			}
			editor.context2D.fillStyle = "red";
			editor.context2D.fillText(editor._FPS, 100, 100);
			
			
			//渲染光标
			if(editor.fileList[editor.open_index].cursor.row>editor.fileList[editor.open_index].start_row){
				if(editor.fileList[editor.open_index].cursor.row<editor.fileList[editor.open_index].start_row+maxL){
				if (editor.fileList[editor.open_index].cursor.status) {
					
					editor.context2D.fillStyle = "red";
					//console.log(editor.fileList[editor.open_index].cursor.row,editor.fileList[editor.open_index].start_row);
					var point=editor.getPosition(editor.fileList[editor.open_index].cursor.row-editor.fileList[editor.open_index].start_row,editor.fileList[editor.open_index].cursor.column);
					editor.context2D.fillText(editor.fileList[editor.open_index].cursor.key, point["cursor_x"], point["cursor_y"]);
					}
				}
			}
		};
		
		//根据行列 获取位置
		editor.getPosition=function(row,column){
			row=parseInt(row);
			column=parseInt(column);
			var row_string=editor.fileList[editor.open_index].content[row-1+editor.fileList[editor.open_index].start_row];
			if(column>row_string.length){
				column=row_string.length;
			}
			var cursor_x=editor.offset_fliechar_x;
			var width=0;
			for (var c in row_string){
				if(parseInt(c)==column){
					break; 
				}else{
					cursor_x = cursor_x + editor.context2D.measureText(row_string[c]).width;
					width=editor.context2D.measureText(row_string[c]).width;
				}
			}
			var cursor_y=editor.offset_fliechar_y+editor.row_height*(row);
			return {"cursor_x":cursor_x,"cursor_y":cursor_y,"height":editor.row_height,"width":width};
		};
		
		
        function getPointOnCanvas(canvas, x, y) {
            var bbox = canvas.getBoundingClientRect();
			var point={layerX:x-canvas.offsetLeft,layerY:y-canvas.offsetTop};
            return point;
        }
		
		//根据点击的位置获取行列
		editor.setCursor=function(point){
			//y取相差最小的
            var offY = 1000;
            var offX = 1000;
            var _row=1;
            var _column=0;
			for(var row_index in  editor.fileList[editor.open_index].content){
				var row_px=editor.offset_fliechar_y+editor.row_height*parseInt(row_index);
				var _offy = point.layerY - row_px;
				if(_offy>0){
					if (Math.abs(_offy) - offY<0) {
						offY=_offy;
						_row=parseInt(row_index)+1;
					}
				}
			}
			
			_row=_row+editor.fileList[editor.open_index].start_row;
			if(_row>editor.fileList[editor.open_index].content.length){
				_row=editor.fileList[editor.open_index].content.length;
			}
			
			var column_string=editor.fileList[editor.open_index].content[_row-1];

			var column_px=editor.offset_fliechar_x;
			for(var column_index in column_string){
				
				var column_px = column_px + Math.round(editor.context2D.measureText(column_string[column_index]).width);
				var _offx = point.layerX - column_px;
				if (Math.abs(_offx) < offX) {
					offX=_offx;
					if(_offx>0){
						_column=parseInt(column_index)+1;
					}else{
						_column=parseInt(column_index);
					}
					if(_column>column_string.length){
						_column=column_string.length;
					}
					
                }
			}
			
            editor.fileList[editor.open_index].cursor.row = _row;
			editor.fileList[editor.open_index]._start_row=_row;
            editor.fileList[editor.open_index].cursor.column = _column;
			
		}
		
		
		editor.setMoveCursor_end=function(point){
			//y取相差最小的
            var offY = 1000;
            var offX = 1000;
            var _row=1;
            var _column=0;
			for(var row_index in  editor.fileList[editor.open_index].content){
				var row_px=editor.offset_fliechar_y+editor.row_height*parseInt(row_index);
				var _offy = point.layerY - row_px;
				if(_offy>0){
					if (Math.abs(_offy) - offY<0) {
						offY=_offy;
						_row=parseInt(row_index)+1;
					}
				}
			}
			
			_row=_row+editor.fileList[editor.open_index].start_row;
			if(_row>editor.fileList[editor.open_index].content.length){
				_row=editor.fileList[editor.open_index].content.length;
			}
			
			var column_string=editor.fileList[editor.open_index].content[_row-1];

			var column_px=editor.offset_fliechar_x;
			for(var column_index in column_string){
				
				column_px = column_px + editor.context2D.measureText(column_string[column_index]).width;
				
				var _offx = point.layerX - column_px;
				if (Math.abs(_offx) < offX) {
					offX=_offx;
					if(_offx>0){
						_column=parseInt(column_index)+1;
					}else{
						_column=parseInt(column_index);
					}
					if(_column>column_string.length){
						_column=column_string.length;
					}
					
                }
			}
			editor.fileList[editor.open_index].cursor.row = _row;
            editor.fileList[editor.open_index].cursor.column = _column;
			var new_row={row:_row,column:_column};
			if(editor.fileList[editor.open_index].select_start==null){
				editor.fileList[editor.open_index].select_start=new_row;
				editor.fileList[editor.open_index]._select_start=new_row;
			}else{
				if(_row==editor.fileList[editor.open_index].select_start["row"]){
					if(_column>editor.fileList[editor.open_index].select_start["column"]){
						editor.fileList[editor.open_index].select_end=new_row;
					}else if(_column<editor.fileList[editor.open_index].select_start["column"]){
						editor.fileList[editor.open_index].select_end=editor.fileList[editor.open_index]._select_start;
					    editor.fileList[editor.open_index].select_start=new_row;
					}
				}else if(_row>editor.fileList[editor.open_index].select_start["row"]){
					editor.fileList[editor.open_index].select_end=new_row;
				}else{
					editor.fileList[editor.open_index].select_end=editor.fileList[editor.open_index]._select_start;
					editor.fileList[editor.open_index].select_start=new_row;
					
				}
			}
			
		}
		
		//鼠标左键按下事件
        editor.doMouseDown = function (ev) {
			
            editor.fileList[editor.open_index].select_end=null;
			editor.fileList[editor.open_index].select_start=null;
			//console.dir(ev);
            var Point = getPointOnCanvas(ev.target, ev.pageX, ev.pageY);
			
            editor.mousedown_position = ev;
			if(Point["layerX"]>editor.offset_fliechar_x && Point["layerY"]>editor.offset_fliechar_y){
				if(Point["layerX"]<editor.width-editor.rightScrollRect_bg["width"]){
					editor.setCursor(Point);
			   }else{
				   //右侧滑块
				   console.log("右侧滑块");
			   }
			}else if(Point["layerX"]<=editor.offset_fliechar_x && Point["layerY"]>editor.offset_fliechar_y){
				//行号
				console.log("行号");
			}else if(Point["layerY"]<=editor.offset_fliechar_y){
				//头部
				console.log(Point["layerY"]+":"+ev.layerY+":"+editor.offset_fliechar_y);
				console.log("头部");
			}
        };
        editor.doMouseUp = function (ev) {
            editor.mouseup_position = ev;
			editor.mousedown_position=null;
			editor.fileList[editor.open_index]._start_row=editor.fileList[editor.open_index].start_row;
            $("#in").focus();
            $("#in").val("");
        };
		
		//editor._start_row=0;
        editor.doMouseMove = function (ev) {
            
			if(editor.mousedown_position){
				//console.dir(ev);
				var Point_end = getPointOnCanvas(ev.target, ev.pageX, ev.pageY);
				var point_down=getPointOnCanvas(editor.mousedown_position.target, editor.mousedown_position.pageX, editor.mousedown_position.pageY);
				if(point_down["layerX"]>editor.offset_fliechar_x && point_down["layerY"]>editor.offset_fliechar_y){
					if(point_down["layerX"]<editor.width-editor.rightScrollRect_bg["width"]){
						editor.setMoveCursor_end(Point_end);
				   }else{
					   //右侧滑块
					   var maxL=editor.getMaxRows();
					   //var Rc=editor.getRC(Point_end);
					   console.log(Point_end.layerY-point_down.layerY);
					   var row=editor.doMouseDownSollre(Math.abs(Point_end.layerY-point_down.layerY));
					   if(Point_end.layerY-point_down.layerY>0){
						   if(editor.fileList[editor.open_index]._start_row+row>editor.fileList[editor.open_index].content.length-maxL){
							    editor.fileList[editor.open_index].start_row=editor.fileList[editor.open_index].content.length-maxL;
							}else{
								editor.fileList[editor.open_index].start_row=editor.fileList[editor.open_index]._start_row+row;
							}
						}else{
							if(editor.fileList[editor.open_index]._start_row-row<0){
							    editor.fileList[editor.open_index].start_row=0
							}else{
								editor.fileList[editor.open_index].start_row=editor.fileList[editor.open_index]._start_row-row;
							}
						}
				   }
				}else if(point_down["layerX"]<=editor.offset_fliechar_x && point_down["layerY"]>editor.offset_fliechar_y){
					//行号
					console.log("行号");
				}else if(point_down["layerY"]<=editor.offset_fliechar_y){
					//头部
					console.log("头部");
				}
				
			}
        };
		//滑块移动量转换为行数
		editor.doMouseDownSollre=function(px){
			var maxL=editor.getMaxRows();
			var _px=(editor.rightScrollRect_bg["height"]-editor.rightScrollRect["height"])/(editor.fileList[editor.open_index].content.length-maxL);
			return Math.round(px/_px);
		};
		
        editor.doKeyDown = function (ev) {
            var keyID = ev.keyCode ? ev.keyCode : ev.which;
			var maxL=editor.getMaxRows();
			var cursor = editor.fileList[editor.open_index].cursor;
			var row=cursor.row;
			var column=cursor.column;
            if (keyID == 8) {
				console.log(row);
				var row_string=editor.fileList[editor.open_index].content[row-1];
				if(column>0){
					var new_row_string=row_string.substring(0,column-1)+row_string.substring(column);
					editor.fileList[editor.open_index].content[row-1]=new_row_string;
					editor.fileList[editor.open_index].cursor.column=column-1;
				}else{
					if(row-2>=0){
						var up_row_string=editor.fileList[editor.open_index].content[row-2];
						var new_row_string=up_row_string+row_string;
						editor.fileList[editor.open_index].content[row-2]=new_row_string;
						editor.fileList[editor.open_index].content.splice(row-1,1);
						
						editor.fileList[editor.open_index].cursor.row=row-1;
						editor.fileList[editor.open_index].cursor.column=up_row_string.length;
					}
				}
				
            }else if(keyID==38){
				
				if(row-1>0){
				   editor.fileList[editor.open_index].cursor.row=row-1;
				   if(editor.fileList[editor.open_index].cursor.row<=editor.fileList[editor.open_index].start_row){
					   editor.fileList[editor.open_index].start_row-=1;
				   }
				}
				
			}else if(keyID==40){
				
				if(row+1<=editor.fileList[editor.open_index].content.length){
				   editor.fileList[editor.open_index].cursor.row=row+1;
				   if(editor.fileList[editor.open_index].cursor.row>editor.fileList[editor.open_index].start_row+maxL){
					   editor.fileList[editor.open_index].start_row+=1;
				   }
				}
			}else if(keyID==37){
				
				if(column-1>=0){
					editor.fileList[editor.open_index].cursor.column=column-1;
				}else{
					if(row-1>0){
						editor.fileList[editor.open_index].cursor.row=row-1;
						editor.fileList[editor.open_index].cursor.column=editor.fileList[editor.open_index].content[row-1].length;
					}
				}
				
			}else if(keyID==39){
				
				if(column+1<=editor.fileList[editor.open_index].content[row-1].length){
					editor.fileList[editor.open_index].cursor.column=column+1;
				}else{
					if(row+1<=editor.fileList[editor.open_index].content.length){
						
						editor.fileList[editor.open_index].cursor.row=row+1;
						editor.fileList[editor.open_index].cursor.column=0;
					}
				}
			}

        };
		
		//鼠标滑动事件
		editor.mouseScroll=function(ev){
			editor.mousescroll_position=ev;
			//console.dir(ev);
			var type = ev.type;
            if (type == 'DOMMouseScroll' || type == 'mousewheel') {
                ev.delta = (ev.wheelDelta) ? ev.wheelDelta / 120 : -(ev.detail || 0) / 3;
            }
            
			var maxL=editor.getMaxRows();
			if(ev.delta==-1){
				//向下滚动
				
				if(editor.fileList[editor.open_index].start_row+1<=editor.fileList[editor.open_index].content.length-maxL){
					editor.fileList[editor.open_index].start_row=editor.fileList[editor.open_index].start_row+1;
					
				}
			}else if(ev.delta==1){
				//向上滚动
				if(editor.fileList[editor.open_index].start_row-1>=0){
					editor.fileList[editor.open_index].start_row=editor.fileList[editor.open_index].start_row-1;
				}
			}
			
			
			
		};

        $("#in").bind("input", function (e) {
            var text = $("#in").val();
            var arr = text.split('');
            for (var i in arr) {
				//editor.fileList[editor.open_index].contentAdd.push(arr[i]);
				
                var cursor = editor.fileList[editor.open_index].cursor;
				var row=cursor.row;
				var column=cursor.column;
				if(arr[i].charCodeAt()==10){
					var row_string=editor.fileList[editor.open_index].content[row-1];
					var old_row_string=row_string.substring(0,column);
					var new_row_string=row_string.substring(column);
					editor.fileList[editor.open_index].content[row-1]=old_row_string;
					editor.fileList[editor.open_index].content.splice(row,0,new_row_string);
					editor.fileList[editor.open_index].cursor.row=row+1;
					editor.fileList[editor.open_index].cursor.column=0;
				}else{
					var row_string=editor.fileList[editor.open_index].content[row-1];
					var new_row_string=row_string.substring(0,column)+arr[i]+row_string.substring(column);
					editor.fileList[editor.open_index].content[row-1]=new_row_string;
					editor.fileList[editor.open_index].cursor.column=column+1;
				}  
            }

            $("#in").val("");
        });
		
		//事件列表
		editor.canvas.addEventListener("mousedown", editor.doMouseDown, false);
        editor.canvas.addEventListener('mousemove', editor.doMouseMove,false);
        editor.canvas.addEventListener('mouseup', editor.doMouseUp, false);
        window.addEventListener('keydown', editor.doKeyDown, true);
		var isIE=navigator.userAgent.toUpperCase().indexOf("MSIE")>0 ? true:false;
		if(isIE){
			editor.canvas.attachEvent('onmousewheel',editor.mouseScroll); 
			//window.attachEvent('onkeydown', editor.doKeyDown);
		}else{
			editor.canvas.addEventListener('DOMMouseScroll', editor.mouseScroll, true);
			//window.addEventListener('keydown', editor.doKeyDown, true);
		}
        

		
        isChina = function (temp) {
            //var re=/[^/u4e00-/u9fa5]/;
            if (/.*[\u4e00-\u9fa5]+.*$/.test(temp)) return false;
            return true;
        };

        checkFile = function (efile) {
            var bl = false;
            for (var _efile in editor.fileList) {
                if (_efile.path == efile.path) {
                    return true;
                }
            }
            return bl;
        };
        return editor;
    }
}